package com.xtsoft.platform.base.database.controller;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.xtsoft.core.controller.GenericController;
import com.xtsoft.core.repository.QueryFilter;
import com.xtsoft.core.repository.QueryResult;
import com.xtsoft.core.utils.ResultMsg;
import com.xtsoft.core.utils.StringUtils;

import com.xtsoft.platform.base.database.domain.DbConnect;
import com.xtsoft.platform.base.database.service.DbConnectService;
import com.xtsoft.platform.base.system.domain.SysUser;
import com.xtsoft.platform.globe.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.sql.SQLException;
import java.text.ParseException;

/**
 * 
 * @ClassName: DbConnect
 *             <p>
 *             数据库连接处理类
 *             </p>
 * @author: Codegen-代码生成器
 * @date: 2019年12月3日 上午10:59:46
 */
@Tag(name ="数据库连接--处理接口" )
@RestController
public class DbConnectController extends GenericController {

	private final Logger log = LoggerFactory.getLogger(DbConnectController.class);

	@Autowired
	private DbConnectService dbConnectService;

	/**
	 * <p>
	 * 新增一个数据库连接
	 * </p>
	 * 
	 * @param dbConnect 要新增的数据库连接
	 * @return ResponseEntity<ResultMsg>, ResultMsg的Data中包含 数据库连接
	 * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@PostMapping("/dbConnect/add")
	@Operation(summary="新增，根据前台传递的数据库连接新增")
	@Parameter(name = "sysDashboard",description = "要新增的数据库连接")
	public ResponseEntity<ResultMsg> add(
			@RequestBody DbConnect dbConnect)
			throws URISyntaxException {
		if (null == dbConnect) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "新增数据库连接失败，传递的数据库连接为空"), HttpStatus.OK);
		}

		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("新增数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		if (!StringUtils.isEmpty(dbConnect.getDbConnectId())) {
			log.info("新增数据库连接失败，新数据库连接不能具有DbConnectId属性值", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "新增数据库连接失败，新数据库连接不能具有DbConnectId属性值"),
					HttpStatus.OK);
		}

		DbConnect result = dbConnectService.save(dbConnect);
//		log.info("新增数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "新增成功", result), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 更新一个数据库连接
	 * </p>
	 * 
	 * @param dbConnect 要更新的数据库连接
	 * @return ResponseEntity<ResultMsg>, json格式
	 * @throws URISyntaxException 如果URI语法不正确，则抛URI语法异常
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@PostMapping("/dbConnect/update")
	@Operation(summary="更新，根据传递的 数据库连接更新实体")
	@Parameter(name = "dbConnect",description = "要更新的数据库连接")
	public ResponseEntity<ResultMsg> update(
			@RequestBody DbConnect dbConnect)
			throws URISyntaxException {
		if (null == dbConnect) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新数据库连接失败，传递的数据库连接为空"), HttpStatus.OK);
		}
//		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
//		log.info("单条更新数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		// 若 数据库连接无主键值，说明调用错误
		if (StringUtils.isBlank(dbConnect.getDbConnectId())) {
//			log.info("单条更新数据库连接失败，数据库连接对象DbConnectId无属性值", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "更新失败，数据库连接对象DbConnectId无属性值"), HttpStatus.OK);
		}

		DbConnect result = dbConnectService.save(dbConnect);
//		log.info("单条更新数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "更新成功", result), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 查询数据库连接列表，若分页，则页码信息在Request的参数中，包括当前页，每页记录数
	 * </p>
	 * 
	 * @return ResponseEntity<QueryResult<DbConnect>>，json格式
	 * @throws URISyntaxException 如果出错，则产生页码信息的 HTTP headers
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@GetMapping("/dbConnect/getAll")
	@Operation(summary="查询，根据传递的条件查询数据库连接列表，条件参数在Request中")
	
	public ResponseEntity<ResultMsg> getAll()
			throws URISyntaxException, JsonParseException, JsonMappingException, IOException, ParseException {
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("获取数据库连接列表开始......", user.getLoginId(), user.getUsername(), getClientIp());
		QueryFilter<DbConnect> filter = new QueryFilter<DbConnect>(DbConnect.class);
		filter.addFilterFromRequest(request);
		QueryResult<DbConnect> result = dbConnectService.anyQuery(filter);
		if (null == result || null == result.getResultList() || result.getResultList().size() < 0) {
			log.info("获取数据库连接列表失败", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取数据库连接列表失败"), HttpStatus.OK);
		}
		log.info("获取数据库连接列表成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取列表成功", result.getResultList()), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据数据库连接唯一ID值获取数据库连接
	 * </p>
	 * 
	 * @param id 数据库连接唯一ID值
	 * @return ResponseEntity<DbConnect>
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@GetMapping("/dbConnect/get/{id}")
	@Operation(summary="获取单个数据库连接，若根据数据库连接唯一Id获取到了多个对象则发生异常")
	@Parameter(name = "id",description = "对象唯一Id")
	public ResponseEntity<ResultMsg> get(@PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个数据库连接失败，未给定数据库连接的唯一标识"), HttpStatus.OK);
		}
//		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
//		log.info("获取数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		DbConnect dbConnect = dbConnectService.get(id);
		/*
		 * <p> ofNullable执行逻辑：如果对象为空，则执行orElse，否则执行.map... return
		 * Optional.ofNullable(sysRole).map(result -> new ResponseEntity<>(result,
		 * HttpStatus.OK)) .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
		 */

		if (null == dbConnect) {
//			log.info("获取数据库连接失败", user.getLoginId(), user.getUsername(), getClientIp());
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "获取单个数据库连接失败，给定的数据库连接可能被删除"), HttpStatus.OK);
		}
//		log.info("获取数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "获取成功", dbConnect), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据数据库连接唯一ID值删除单个数据库连接
	 * </p>
	 * 
	 * @param id 数据库连接唯一ID值
	 * @return ResponseEntity,json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@GetMapping("/dbConnect/delete/{id}")
	@Operation(summary="删除单个数据库连接")
	@Parameter(name = "id",description = "数据库连接唯一Id")
	public ResponseEntity<ResultMsg> delete(
			@PathVariable String id) {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "删除单个数据库连接失败，未给定数据库连接的唯一标识"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("删除单条数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		dbConnectService.remove(id);
		log.info("删除单条数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "删除成功"), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据数据库连接唯一ID值集合，批量删除数据库连接
	 * </p>
	 * 
	 * @param ids 数据库连接唯一ID值集合
	 * @return ResponseEntity<ResultMsg>,返回结果中有删除的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@PostMapping("/dbConnect/deleteBatch")
	@Operation(summary="删除数据库连接集合")
	@Parameter(name = "ids",description = "逗号分隔的数据库连接Id集合")
	public ResponseEntity<ResultMsg> deleteBatch(
			@RequestParam String ids) {
		if (StringUtils.isBlank(ids)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "批量删除数据库连接失败，未给定数据库连接的唯一标识集合"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量删除数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		long rows = dbConnectService.deleteBatch(ids);
		log.info("批量删除数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "批量删除数据库连接成功", rows), HttpStatus.OK);
	}

	/**
	 * <p>
	 * 根据数据库连接唯一ID值集合，批量更新数据库连接
	 * </p>
	 * 
	 * @param ids            数据库连接唯一ID值集合
	 * @param properityName  数据库连接要更新的属性名，不带类名
	 * @param properityValue 数据库连接要更新的属性值
	 * @return ResponseEntity<ResultMessage>,返回结果中有更新的记录数，json格式
	 * @author Codegen-代码生成器
	 * @date 2020-08-14 12:06:18
	 */
	@PostMapping("/dbConnect/updateBatch")
	@Operation(summary="更新数据库连接集合")

	@Parameters({
			@Parameter(name = "properityName", description="要更新的属性名不带类名，只能是类单个属性名且不能是集合类型", required = false),
			@Parameter(name = "properityValue", description="属性值", required = false),
			@Parameter(name = "ids", description="逗号分隔的仪表盘Id集合", required = false)})
	public ResponseEntity<ResultMsg> updateBatch(
		@RequestParam String properityName, 
		@RequestParam String properityValue,
		@RequestParam String ids) {
		if (StringUtils.isBlank(ids) || StringUtils.isBlank(properityValue) || StringUtils.isBlank(properityName)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "批量更新数据库连接失败，未给定数据库连接的唯一标识集合或属性名或属性值"),
					HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("批量更新数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		long rows = dbConnectService.updateBatch(properityName, properityValue, ids);
		log.info("批量更新数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "批量更新数据库连接成功", rows), HttpStatus.OK);
	}

	/**
	 * 
	 * <p>
	 * 方法的功能说明
	 * </p>
	 * 
//	 * @param ids
	 * @return
	 * @return ResponseEntity<ResultMsg>
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws @author  shijunwei
	 * @date 2020年8月17日
	 * @time 下午5:49:26
	 */
	@GetMapping("/dbConnect/test/{id}")
	@Operation(summary="测试数据库连接集合")
	@Parameter(name = "id",description = "数据库连接唯一Id")
	public ResponseEntity<ResultMsg> test(
		@PathVariable String id)
			throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException {
		if (StringUtils.isBlank(id)) {
			return new ResponseEntity<ResultMsg>(new ResultMsg(false, "测试单个数据库连接失败，未给定数据库连接的唯一标识"), HttpStatus.OK);
		}
		SysUser user = (SysUser) SecurityUtils.getLoginedUser();
		log.info("测试单条数据库连接开始......", user.getLoginId(), user.getUsername(), getClientIp());
		DbConnect dbc = dbConnectService.get(id);
		if (!dbConnectService.test(dbc)) {
			log.info("测试单条数据库连接失败", user.getLoginId(), user.getUsername(), getClientIp());
		    return new ResponseEntity<ResultMsg>(new ResultMsg(false, "测试失败"),HttpStatus.OK);
		}
		log.info("测试单条数据库连接成功",user.getLoginId(), user.getUsername(), getClientIp());
		return new ResponseEntity<ResultMsg>(new ResultMsg(true, "测试成功"), HttpStatus.OK);
	}

}
